<template>
  <div>
    <el-form label-position="left" :label-width="props.labelWidth" ref="formRef" :model="formModel" label-suffix=":" :rules="formRules">
      <el-row :gutter="6" class="parent">
        <el-col v-bind="formItemLayout" :span="12" v-for="(item, index) in formItems" v-show="index < maxCount">
          <el-form-item :label="item.label" :prop="item.prop" v-bind="item.formItemProps || {}">
            <component style="width: 100%;" :key="item.prop + index" :is="resolveComponentType(item)" :rules="item.rules" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-space>
            <el-button :icon="Search" type="primary" @click="search" :loading="props.searchLoading">查询</el-button>
            <el-button :icon="RefreshRight" @click="reset">重置</el-button>
            <slot name="action"></slot>
            <el-badge v-if="items.length > 2" :value=" !collapsed ? formItems.length - maxCount : ''" class="item">
              <el-link type="primary" @click="toggleCollapsed"
                >{{ collapsed ? '精简模式' : '高级模式' }}
                <!-- <span v-show="!collapsed">({{ formItems.length - maxCount }})</span> -->
              </el-link>
            </el-badge>
          </el-space>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, h } from 'vue';
import { ElDatePicker, ElForm, ElInput, ElOption, ElSelect } from 'element-plus';

const formItemLayout = {
  xs: 24,
  sm: 12,
  md: 8,
  lg: 6,
}

// 定义props
const props = defineProps({
  items: {
    type: Array,
    required: true,
  },
  modelValue: {
    type: Object,
    required: true,
    default: () => ref({})
  },
  rules: {
    type: Object,
    default: () => ({}),
  },
  labelWidth: {
    type: Number,
    default: 100,
  },
  searchLoading: {
    type: Boolean,
  }
});

// 定义emits
const emit = defineEmits(['update:modelValue']);

const maxCount = ref(2)

// 初始化表单ref和数据模型
const formRef = ref(null);
const collapsed = ref(false)

// 计算属性，处理items，添加默认属性等
const formItems = computed(() =>
  props.items.map((item) => ({
    ...item,
    // 为没有明确指定rules的item添加默认规则
    rules: item.rules || {},
  }))
);

const reset = () => {
  formRef.value.resetFields()
  emit('update:modelValue', {});
  emit('onFinish', {});
}


const search = () => {
  formRef.value.validate((valid) => {
    if (valid) emit('onFinish', props.modelValue)
  })
}


const toggleCollapsed = () => {
  if (collapsed.value) {
    maxCount.value = 2
  } else {
    maxCount.value = 999
  }
  collapsed.value = !collapsed.value
}
const formModel = ref(props.modelValue);


const handlChange = (value, item) => {
  emit('update:modelValue', { ...props.modelValue, [item.prop]: value });
}

const selectedValue = ref('')
// 根据valueType解析组件类型
const resolveComponentType = (item) => {
  const { options = [], valueType, fieldProps } = item

  const commonProps = {
    modelValue: props.modelValue[item.prop],
    'onUpdate:modelValue': e => handlChange(e, item),
    clearable: true
  }

  switch (valueType) {

    case 'input':
      return h(ElInput, { ...commonProps, ...fieldProps },);

    case 'select':
      return h(ElSelect,
        {
          ...commonProps,
          ...fieldProps
        },
        options?.map?.(option => h(ElOption, { value: option.value, label: option.label || option.text })),
      );

      case 'date':
      return h(ElDatePicker,
        {
          ...commonProps,
          ...fieldProps
        }
      );

    default:
      throw new Error(`Unsupported valueType: ${valueType}`);
  }
};



// 将外部传入的rules与每项的rules合并
const formRules = computed(() => {
  const mergedRules = {};
  props.items.forEach((item) => {
    if (item.prop && item.rules) {
      mergedRules[item.prop] = item.rules;
    }
  });
  return { ...props.rules, ...mergedRules };
});
</script>

<style scoped>
.parent> :last-child {
  margin-left: auto;
  text-align: end
}
</style>
